package com.teamwhole.modules.act.web;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.teamwhole.common.mapper.JsonMapper;
import com.teamwhole.common.model.ResultInfo;
import com.teamwhole.modules.act.service.ActProcessService;
import com.teamwhole.modules.act.utils.ActUtils;

import jersey.repackaged.com.google.common.collect.Maps;


/**
 * 流程定义相关资源
 * 
 * @author ZGJ
 *
 */
@Component
@Path("/act/process")
@Consumes("application/json;charset=utf-8")
@Produces("application/json;charset=utf-8")
public class ActProcessResource {

    @Autowired
    private ActProcessService actProcessService;
    
    /**
     * 流程定义列表
     * @param category
     * @return
     */
    @Path("list")
    @GET
	public Object list(@QueryParam("category") String category) {
		List<Object[]> list = actProcessService.processList(category);
		List<Map<String, Object>> mapList = Lists.newArrayList();
		for (Object[] obj : list) {
			Map<String, Object> map = Maps.newHashMap();
			String process = JSON.toJSONString((ProcessDefinition) obj[0], ActUtils.getProcessDefinitionFilter());
			String deployment = JSON.toJSONString((Deployment) obj[1], ActUtils.getDeploymentEntityFilter());
			map.put("process", JsonMapper.fromJsonString(process, Map.class));
			map.put("deployment", JsonMapper.fromJsonString(deployment, Map.class));
			mapList.add(map);
		}
		return mapList;
	}
    
    /**
     * 运行中的实例列表
     * @param procInsId
     * @param procDefKey
     * @return
     */
    @Path("list-running")
    @GET
    public Object runningList(@QueryParam("procInsId")String procInsId, @QueryParam("procDefKey")String procDefKey) {
        List<ProcessInstance> list = actProcessService.runningList(procInsId, procDefKey);
        return list;
    }
    
    /**
     * 部署流程 - 保存
     * @param fdmp
     * @return
     */
    @Path("/deploy")
    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)    // FormDataMultiPart fdmp   String category, MultipartFile file
    public ResultInfo deploy(FormDataMultiPart fdmp) {
        return actProcessService.deploy(fdmp);
    }
    
    /**
     * 读取资源，通过部署ID
     * @param procDefId
     * @param proInsId
     * @param resType
     * @return
     * @throws Exception
     */
    @Path("resource/read")
    @GET
    @Produces({"image/png", MediaType.APPLICATION_XML})
    public Response resourceRead(@QueryParam("procDefId") String procDefId,
            @QueryParam("proInsId") String proInsId, @QueryParam("resType") String resType)
            throws Exception {
        InputStream resourceAsStream = actProcessService.resourceRead(procDefId, proInsId, resType);
        return "xml".equalsIgnoreCase(resType)
                ? Response.ok(resourceAsStream, MediaType.APPLICATION_XML_TYPE).build()
                : Response.ok(resourceAsStream, "image/png").build();
    }
    
    
//    /**
//     * 设置流程分类
//     * @param procDefId
//     * @param category
//     * @return
//     */
//    @Path("updateCategory")
//    @GET
//    public ResultInfo updateCategory(@QueryParam("procDefId") String procDefId, @QueryParam("category") String category) {
//        actProcessService.updateCategory(procDefId, category);
//        return ResultInfo.ok();
//    }
//    
//    /**
//     * 挂起、激活流程实例
//     * @param state
//     * @param procDefId
//     * @param redirectAttributes
//     * @return
//     */
//    @Path("updateState")
//    @GET
//    public ResultInfo updateState(String state, String procDefId) {
//        actProcessService.updateState(state, procDefId);
//        return ResultInfo.ok();
//    }
//    
//    /**
//     * 将部署的流程转换为模型
//     * @param procDefId
//     * @return
//     * @throws UnsupportedEncodingException
//     * @throws XMLStreamException
//     */
//    @Path("convert/toModel")
//    public ResultInfo convertToModel(String procDefId) throws UnsupportedEncodingException, XMLStreamException {
//        //org.activiti.engine.repository.Model modelData = actProcessService.convertToModel(procDefId);
//        //redirectAttributes.addFlashAttribute("message", "转换模型成功，模型ID="+modelData.getId());
//        actProcessService.convertToModel(procDefId);
//        return ResultInfo.ok();
//    }
//    
//    /**
//     * 导出图片文件到硬盘
//     * @param exportDir
//     * @return
//     * @throws IOException
//     */
//    @Path(value = "export/diagrams")
//    public List<String> exportDiagrams(@Value("#{APP_PROP['activiti.export.diagram.path']}") String exportDir) throws IOException {
//        List<String> files = actProcessService.exportDiagrams(exportDir);;
//        return files;
//    }
    
    /**
     * 删除部署的流程，级联删除流程实例
     * @param deploymentId 流程部署ID
     */
    @Path("delete")
    @POST
    public ResultInfo delete(String deploymentId) {
        actProcessService.deleteDeployment(deploymentId);
        return ResultInfo.ok();
    }
 
//    /**
//     * 删除流程实例
//     * @param procInsId 流程实例ID
//     * @param reason 删除原因
//     */
//    @Path("deleteProcIns")
//    @POST
//    public ResultInfo deleteProcIns(String procInsId, String reason) {
//        if (StringUtils.isBlank(reason)) {
//            //addMessage(redirectAttributes, "请填写删除原因");
//        } else {
//            actProcessService.deleteProcIns(procInsId, reason);
//            //addMessage(redirectAttributes, "删除流程实例成功，实例ID=" + procInsId);
//        }
//        return ResultInfo.ok();
//    }
    
}
